#!/usr/bin/env python
# -*- coding: utf-8 -*-
# output. data from DB.
import locale
import EkikaraDb
import TimetableExporter


class OudiaCsv(TimetableExporter.TimetableExporter):
    def __init__(self,
                 db,
                 timetable_id,
                 logger,
                 argv,
                 encode=None,
                 newline=None,
                 status_option=False,
                 console_encode=locale.getpreferredencoding()):
        TimetableExporter.TimetableExporter.__init__(self, db, timetable_id, logger, argv, encode, newline,
                                                     status_option=status_option,
                                                     console_encode=console_encode)
        # override self.encode
        if not self.encode:
            self.encode = 'CP932'
        if not self.newline:
            self.newline = u"\r\n"      # CRLF
        self.target = EkikaraDb.Timetable(self.db, timetable_id, logger)

    def oudiaCsvLines(self):
        trainNumberList = []
        for item in self.target.trainNumberList():
            trainNumberList.append(item['train_number'])
        header = self.target.trainHeaderList(self.target.trainNumberList())
        for row in self.target.getTitleColumn():
            line = [row['title'], row['arrival_departure'], ]
            if row['station_index'] != None:
                # station name
                if row['arrival_departure'] == u"着":
                    line += self.target.trainArrivalList(row['title'], self.target.trainNumberList())
                elif row['arrival_departure'] == u"発":
                    line += self.target.trainDepartureList(row['title'], self.target.trainNumberList())
                else:
                    self.logger.error("unknown arrival departure [%s]" % (row['arrival_departure']))
            else:
                if row['title'] == u"列車番号":
                    line += trainNumberList
                elif row['title'] == u"列車種別":
                    line += header['type']
                elif row['title'] == u"列車名":
                    line += header['name']
                elif row['title'] == u"号数":
                    line += header['gou']
                elif row['title'] == u"gou_name":
                    line = [u"", row['arrival_departure'], ]    # 号名だけタイトルcolumn無し
                    line += header['gou_name']
                elif row['title'] == u"備考":
                    line += header['note']
                else:
                    self.logger.error("unknown arrival item [%s]" % (row['title']))
            yield line

    def put(self, fout):
        self.target.setTitleColumn()  # 最終的なstationListを元に生成
        attr = self.target.getAttr()
        if attr['updown'] == 'up':
            updown_name = u"上り"
        else:
            updown_name = u"下り"
        self._writeln(fout, u"FileType,OuDia.JikokuhyouCsv.1")
        self._writeln(fout, u"9999年99月")
        self._writeln(fout, u"%s" % (updown_name, ))
        for line in self.oudiaCsvLines():
            #self.logger.debug(line)
            strDetail = u",".join(line)
            self._writeln(fout, strDetail)
